#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, site 
import re, urllib
import datetime, time
import shutil
import sqlite3dbm

from generator import *
from paneo import *
from models import *

from paneo_html import PaneoImage

from sqlobject import *
sqlhub.processConnection = connectionForURI('sqlite://'+ARTICLES_DB)

import web

from mako.template import Template
from mako.lookup import TemplateLookup

TLOOKUP = TemplateLookup(   directories=[PANEO_SITE_DATA_DIR+'/_paneo_data/templates/include/'],
                            input_encoding='utf-8',
                            output_encoding='utf-8',
                            encoding_errors='replace', 
                            default_filters=["none_to_blank", "unicode"],
                            #cache_impl='beaker',
                            #cache_args={
                            #},
                            imports = RENDER_IMPORTS )


#from beaker.cache import CacheManager
#from beaker.util import parse_cache_config_options
#
#cache_opts = {
#    'cache.type': 'file',
#    'cache.data_dir': PANEO_SITE_DATA_DIR + '/_tmp/cache/file/data',
#    'cache.lock_dir': PANEO_SITE_DATA_DIR + '/_tmp/cache/file/lock'
#}
#cache = CacheManager(**parse_cache_config_options(cache_opts))

from beaker import cache

cachemg = cache.CacheManager(cache_regions={
'default' :{
        'type':'memcached',
        'url':'127.0.0.1:11211',
        'expiretime':1,
        'lock_dir': PANEO_SITE_DATA_DIR + '/_tmp/cache/file/lock'
    }
})

class View:

    def __init__(self):
        web.header("Content-Type", "text/html; charset=UTF-8")
        web.header("Cache-Control", "no-cache, must-revalidate")
        web.header("Pragma", "no-cache")

    #@cachemg.cache(expire=60)
    def GET(self,id="index"):

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        pages = dic.get('pages')
        dic.close()

        #新着記事共通
        AT = ArticlesType.select(ArticlesType.q.id == '1').getOne(default=None)

        page = pages.get(id)
        html = page.PaneoMakeHtmlTemplate(id,page)
            
        return html
        #template = Template(    
        #                        html,
        #                        lookup=TLOOKUP,
        #)

        #return template.render( 
        #                        web = web,
        #                        scfg=scfg,
        #                        ua_option = None,
        #                        AT = AT,
        #                        pages = pages,
        #                        bookmark = {},
        #)

class ArticleView:

    def __init__(self):
        web.header("Content-Type", "text/html; charset=UTF-8")
        web.header("Cache-Control", "no-cache, must-revalidate")
        web.header("Pragma", "no-cache")

    #@cachemg.cache(expire=60)
    def GET(self,id=None):

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        pages = dic.get('pages')
        dic.close()

        page = PaneoPage()
        post = Posts.select(Posts.q.slug == id).getOne(default=None)
        if not post :
            return web.notfound()

        return page.PaneoMakeHtmlTemplate(id,None,post)

        #template = Template(    
        #                        html,
        #                        lookup=TLOOKUP,
        #)

        #return template.render( 
        #                        web = web,
        #                        scfg=scfg,
        #                        ua_option = None,
        #                        AT = AT,
        #                        pages = pages,
        #                        bookmark = {},
        #)

#class ViewCss:
#
#    def __init__(self):
#        web.header("Content-Type", "text/css; charset=UTF-8")
#        web.header("Cache-Control", "no-cache, must-revalidate")
#        web.header("Pragma", "no-cache")
#
#    def GET(self,id="index"):
#
#        dic = sqlite3dbm.sshelve.open(PANEO_DB)
#        scfg = dic.get('siteconfig')
#        pages = dic.get('pages')
#        dic.close()
#
#        #新着記事共通
#        AT = ArticlesType.select(ArticlesType.q.id == '1').getOne(default=None)
#
#        page = pages.get(id)
#        html = page.PaneoMakeCssTemplate(id,page)
#
#        template = Template(    
#                                html,
#                                lookup=TLOOKUP,
#        )
#
#        return template.render( 
#                                web = web,
#                                scfg=scfg,
#                                ua_option = None,
#                                AT = AT,
#                                pages = pages,
#                                bookmark = {},
#        )


class StaticView:
    def GET( self, _path ):
        return web.seeother('http://' + web.ctx.host + '/%s/common/%s' % ( PANEO_SITE_DIR , _path ))

from mako import exceptions
        
class TemplateView:

    def __init__(self):
        self.cms = 'pages'
        web.header("Content-Type", "text/html; charset=UTF-8")
        web.header("Cache-Control", "no-cache, must-revalidate")
        web.header("Pragma", "no-cache")

    def GET( self,prefix,template_set,name ):

        filename = TEMPLATE_DIR + '%s_templateset/%s/%s.html' % ( prefix , template_set , name )  

        if os.path.exists( filename ):
            file = codecs.open(filename,"r","utf8")
            html = file.read()
            file.close()

            dic = sqlite3dbm.sshelve.open(PANEO_DB)
            scfg = dic.get('siteconfig')
            pages = dic.get('pages')
            dic.close()

            #新着記事共通
            AT = ArticlesType.select(ArticlesType.q.id == '1').getOne(default=None)

            template = Template(    
                                    html,
                                    lookup=TLOOKUP,
            )

            try:
                return template.render( 
                                        web = web,
                                        paneoimg = PaneoImage,
                                        scfg=scfg,
                                        pages = pages,
                                        ua_option = None,
                                        AT = AT,
                                        bookmark = {},
                )
            except:
                return exceptions.html_error_template().render()

        return "TEMPLATE FILE ERROR"

